//
//  MeController.m
//  EncryPhone
//
//  Created by zhibao on 2023/5/31.
//

#import "MeController.h"
#import "MeIndexCell.h"
#import "MyReplyController.h"
#import "MeContactUsController.h"
#import "AboutController.h"
#import "FuLisheViewController.h"
@interface MeController ()<UITableViewDelegate,UITableViewDataSource>{
    UIImageView *headBgImgView;
    UIImageView *vipIconImgView;
    UILabel *vipTitleLabel;
    UILabel *vipDetailLabel;
}
@property (nonatomic,strong) MYTableView *showTableView;
@property (nonatomic,strong) NSArray *dicArray;
@property (nonatomic,strong) UIActivityViewController *activityVC;
@end

@implementation MeController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    if(![[UserInfoManager sharedManager] isVip]){
        //headBgImgView.image = [UIImage imageNamed:@"me_index_vip_bg_no"];
        vipTitleLabel.text = LocalizedString(@"开通VIP");
        vipTitleLabel.textColor = MyColor(@"#FFC176");
        vipDetailLabel.text = LocalizedString(@"解锁更多高级功能，新功能、新水印优先体验！");
        vipDetailLabel.textColor = MyColor(@"#C4A268");
        vipIconImgView.image = [UIImage imageNamed:@"me_index_vip_no"];
    }else{
        //headBgImgView.image = [UIImage imageNamed:@"me_index_vip_bg"];
        vipTitleLabel.text = LocalizedString(@"VIP会员");
        vipTitleLabel.textColor = MyColor(@"#FFC176");
        vipDetailLabel.text = LocalizedString(@"您可以无限制使用全部功能。");
        vipDetailLabel.textColor = MyColor(@"#A58A5E");
        vipIconImgView.image = [UIImage imageNamed:@"me_index_vip"];
    }
    _dicArray = @[
        @[
            @{@"name":LocalizedString(@"福利社"),@"img":@"me_index_fulishe",@"detail":LocalizedString(@"免费领会员")},
        ],
        @[
            @{@"name":LocalizedString(@"联系我们"),@"img":@"me_index_lianxi",@"detail":@""},
            @{@"name":LocalizedString(@"关于我们"),@"img":@"me_index_about",@"detail":@""},
            @{@"name":LocalizedString(@"分享好友"),@"img":@"me_index_fenxiang",@"detail":@""},
        ],
        @[
            @{@"name":LocalizedString(@"用户协议"),@"img":@"me_index_yonghu",@"detail":@""},
            @{@"name":LocalizedString(@"隐私协议"),@"img":@"me_index_yinsi",@"detail":@""},
            @{@"name":LocalizedString(@"订阅协议"),@"img":@"me_index_dingyue",@"detail":@""},
        ]
    ];
    
    if([MYGlobal share].wechatFlag == 1){
        _dicArray = @[
            @[
                @{@"name":LocalizedString(@"联系我们"),@"img":@"me_index_lianxi",@"detail":@""},
                @{@"name":LocalizedString(@"关于我们"),@"img":@"me_index_about",@"detail":@""},
                @{@"name":LocalizedString(@"分享好友"),@"img":@"me_index_fenxiang",@"detail":@""},
            ],
            @[
                @{@"name":LocalizedString(@"用户协议"),@"img":@"me_index_yonghu",@"detail":@""},
                @{@"name":LocalizedString(@"隐私协议"),@"img":@"me_index_yinsi",@"detail":@""},
                @{@"name":LocalizedString(@"订阅协议"),@"img":@"me_index_dingyue",@"detail":@""},
            ]
        ];
    }
    [_showTableView reloadData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.gk_navTitle = @"个人中心";
    self.view.backgroundColor = MyColor(@"#F0F5FB");
    [self initTableview];
}


-(UIView *)createHeadView{
    
    UIView *headeView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, MY_Screen_W, NAVIH + 15 + 90 + 15)];
    
    headBgImgView = [[UIImageView alloc]init];
    headBgImgView.backgroundColor = MyColor(@"#161413");
    headBgImgView.layer.cornerRadius = 16;
    headBgImgView.userInteractionEnabled = YES;
    [headBgImgView addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithActionBlock:^(id  _Nonnull sender) {
        MyReplyController *controller = [MyReplyController new];
        [self.navigationController pushViewController:controller animated:YES];
    }]];
    [headeView addSubview:headBgImgView];
    [headBgImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.top.mas_equalTo(NAVIH + 15);
        make.right.mas_equalTo(-15);
        make.height.mas_equalTo(pixw(90));
    }];
    
    vipIconImgView = [[UIImageView alloc]initWithImage: [UIImage imageNamed:@"me_index_vip_no"]];
    [headBgImgView addSubview:vipIconImgView];
    [vipIconImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.top.mas_equalTo(23);
        make.width.height.mas_equalTo(20);
    }];
    
    vipTitleLabel = [[UILabel alloc]init];
    vipTitleLabel.text = LocalizedString(@"开通VIP");
    vipTitleLabel.font = MY_SCALE_SemiboldFONT(18);
    vipTitleLabel.textColor = MyColor(@"#FFC176");
    [headBgImgView addSubview:vipTitleLabel];
    [vipTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(vipIconImgView.mas_right).offset(10);
        make.centerY.equalTo(vipIconImgView);
    }];
    
    UILabel *seeLabel = [[UILabel alloc]init];
    seeLabel.text = LocalizedString(@"   查看   ");
    seeLabel.font = MY_SCALE_SemiboldFONT(11);
    seeLabel.layer.masksToBounds = YES;
    seeLabel.backgroundColor = MyColor(@"#FF9B2B");
    seeLabel.textColor = MyColor(@"#ffffff");
    seeLabel.layer.cornerRadius = 14;
    [headBgImgView addSubview:seeLabel];
    [seeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(headBgImgView).offset(-17.5);
        make.height.mas_equalTo(28);
        make.centerY.equalTo(headBgImgView);
    }];
    
    vipDetailLabel = [[UILabel alloc]init];
    vipDetailLabel.text = LocalizedString(@"解锁更多高级功能，新功能、新水印优先体验！");
    vipDetailLabel.numberOfLines = 0;
    vipDetailLabel.lineBreakMode = NSLineBreakByWordWrapping;
    vipDetailLabel.font = MY_SCALE_RegularFONT(12);
    vipDetailLabel.textColor = MyColor(@"#C4A268");
    [headBgImgView addSubview:vipDetailLabel];
    [vipDetailLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(vipIconImgView);
        make.right.equalTo(seeLabel.mas_left).offset(-10);
        make.bottom.equalTo(headBgImgView).offset(-15);
    }];
    
    
    
    return headeView;
}

-(void)initTableview{
    
    self.showTableView = [[MYTableView alloc]initWithFrame:CGRectMake(0,0, MY_Screen_W, MY_Screen_H - barH) style:UITableViewStylePlain];
    self.showTableView.delegate = self;
    self.showTableView.dataSource = self;
    self.showTableView.backgroundColor = [UIColor clearColor];
    self.showTableView.bounces = NO;
    self.showTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.showTableView.tableHeaderView = [self createHeadView];
    self.showTableView.estimatedRowHeight = 0;
    self.showTableView.estimatedSectionFooterHeight = 0;
    self.showTableView.estimatedSectionHeaderHeight = 0;
    if (@available(iOS 15.0, *)) {
        self.showTableView.sectionHeaderTopPadding = 0.0;
    } else {
        // Fallback on earlier versions
    }
    [self.showTableView removeMJRefresh];
    [self.view addSubview:self.showTableView];
    [self.showTableView reloadData];
    [self.showTableView.nodataView removeFromSuperview];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _dicArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [_dicArray[section] count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if([MYGlobal share].wechatFlag == 1){
        if(section == 1){
           return 10;
       }
    }else{
        if(section == 1 || section == 2){
           return 10;
       }
    }
    
    return 0.00001;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier=@"MeIndexCell";
    MeIndexCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell==nil) {
        cell=[[MeIndexCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
    }
    [cell update:_dicArray[indexPath.section][indexPath.row]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *title = _dicArray[indexPath.section][indexPath.row][@"name"];
    if ([title isEqualToString:LocalizedString(@"福利社")]) {
        [[UserInfoManager sharedManager] getUserInfoData:^(BOOL flag) {
            FuLisheViewController *controller = [FuLisheViewController new];
            [self.navigationController pushViewController:controller animated:YES];
        }];
    }else if ([title isEqualToString:LocalizedString(@"联系我们")]) {
        MeContactUsController *controller = [MeContactUsController new];
        [self.navigationController pushViewController:controller animated:YES];
    }else if ([title isEqualToString:LocalizedString(@"关于我们")]) {
        AboutController *controller = [AboutController new];
        [self.navigationController pushViewController:controller animated:YES];
    }else if ([title isEqualToString:LocalizedString(@"欢迎评价")]) {
        
        NSString * urlStr = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/app/id%@?action=write-review",@"6468908434"];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr] options:@{UIApplicationOpenURLOptionsSourceApplicationKey:@YES} completionHandler:^(BOOL success) {
            
        }];
    }else if ([title isEqualToString:LocalizedString(@"分享好友")]) {
        NSString *textToShare = LocalizedString(@"我正在使用盯盯水印相机-工作查岗打卡拍照实时记录上传");//需要分享的文本内容
        UIImage *imageToShare = [UIImage imageNamed:@"com_logo"];//需要分享的图片
        NSURL *urlToShare = [NSURL URLWithString:@"https://apps.apple.com/cn/app/mp3%E8%BD%AC%E6%8D%A2%E5%8A%A9%E6%89%8B-%E9%9F%B3%E9%A2%91%E9%9F%B3%E4%B9%90%E5%BD%A9%E9%93%83%E5%89%AA%E8%BE%91%E7%BC%96%E5%88%9B%E8%BD%AF%E4%BB%B6/id6468908434"];//需要分享的URL
        NSArray *activityItems = @[textToShare, imageToShare, urlToShare];
        self.activityVC = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];
        // 禁用分享渠道
        //            activityVC.excludedActivityTypes = @[UIActivityTypePrint, UIActivityTypeCopyToPasteboard,
        //            UIActivityTypeAssignToContact,UIActivityTypeSaveToCameraRoll];
        // 分享之后的回调
        self.activityVC.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
            if (completed) {
                NSLog(@"成功分享,分享平台%@",activityType);
            }else{
                NSLog(@"取消分享");
            };
        };
        
        [self presentViewController:self.activityVC animated:true completion:nil];
        
    }else if ([title isEqualToString:LocalizedString(@"用户协议")]) {
        WebViewController *controller = [[WebViewController alloc] initWithtitle:LocalizedString(@"用户协议") WithUrl:@"https://docs.qq.com/doc/DRll6a01QaWNiclZE"];
        [[MYGlobal share].lastVC.navigationController pushViewController:controller animated:YES];
    }else if ([title isEqualToString:LocalizedString(@"隐私协议")]) {
        WebViewController *controller = [[WebViewController alloc] initWithtitle:LocalizedString(@"隐私协议") WithUrl:@"https://docs.qq.com/doc/DRmxCb3NSTUF2YnFm"];
        [[MYGlobal share].lastVC.navigationController pushViewController:controller animated:YES];
    }else if ([title isEqualToString:LocalizedString(@"订阅协议")]) {
        WebViewController *controller = [[WebViewController alloc] initWithtitle:LocalizedString(@"订阅协议") WithUrl:@"https://docs.qq.com/doc/DRmlaV0lxYlhjU1Bw"];
        [[MYGlobal share].lastVC.navigationController pushViewController:controller animated:YES];
    }
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    // 圆角角度
    CGFloat radius = 10.f;
    // 设置cell 背景色为透明
    cell.backgroundColor = MyColor(@"#F0F5FB");
    // 创建两个layer
    CAShapeLayer *normalLayer = [[CAShapeLayer alloc] init];
    CAShapeLayer *selectLayer = [[CAShapeLayer alloc] init];
    // 获取显示区域大小
    CGRect bounds = CGRectInset(cell.bounds, [UIScreen mainScreen].bounds.size.width/375 * 14, 0);
    // cell的backgroundView
    UIView *normalBgView = [[UIView alloc] initWithFrame:bounds];
    // 获取每组行数
    NSInteger rowNum = [tableView numberOfRowsInSection:indexPath.section];
    // 贝塞尔曲线
    UIBezierPath *bezierPath = nil;
    
    if (rowNum == 1) {
        // 一组只有一行（四个角全部为圆角）
        bezierPath = [UIBezierPath bezierPathWithRoundedRect:bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(radius, radius)];
        normalBgView.clipsToBounds = NO;
    }else {
        normalBgView.clipsToBounds = YES;
        if (indexPath.row == 0) {
            normalBgView.frame = UIEdgeInsetsInsetRect(bounds, UIEdgeInsetsMake(-1, 0, 0, 0));
            CGRect rect = UIEdgeInsetsInsetRect(bounds, UIEdgeInsetsMake(1, 0, 0, 0));
            // 每组第一行（添加左上和右上的圆角）
            bezierPath = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:(UIRectCornerTopLeft|UIRectCornerTopRight) cornerRadii:CGSizeMake(radius, radius)];
        }else if (indexPath.row == rowNum - 1) {
            normalBgView.frame = UIEdgeInsetsInsetRect(bounds, UIEdgeInsetsMake(0, 0, -1, 0));
            CGRect rect = UIEdgeInsetsInsetRect(bounds, UIEdgeInsetsMake(0, 0, 1, 0));
            // 每组最后一行（添加左下和右下的圆角）
            bezierPath = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:(UIRectCornerBottomLeft|UIRectCornerBottomRight) cornerRadii:CGSizeMake(radius, radius)];
        }else {
            // 每组不是首位的行不设置圆角
            bezierPath = [UIBezierPath bezierPathWithRect:bounds];
        }
    }
    
    // 阴影
    normalLayer.shadowColor = ciThemeColor.CGColor;
    normalLayer.shadowOpacity = 0.2;
    normalLayer.shadowOffset = CGSizeMake(0, 0);
    normalLayer.path = bezierPath.CGPath;
    normalLayer.shadowPath = bezierPath.CGPath;
    
    // 把已经绘制好的贝塞尔曲线路径赋值给图层，然后图层根据path进行图像渲染render
    normalLayer.path = bezierPath.CGPath;
    selectLayer.path = bezierPath.CGPath;
    
    // 设置填充颜色
    normalLayer.fillColor = ciThemeColor.CGColor;
    //    if (indexPath.row % 2 == 0) {
    //            normalLayer.fillColor = [UIColor whiteColor].CGColor;
    //        }else{
    //            normalLayer.fillColor = [UIColor colorWithHexString:@"e9e9e9"].CGColor;
    //        }
    // 添加图层到nomarBgView中
    [normalBgView.layer insertSublayer:normalLayer atIndex:0];
    normalBgView.backgroundColor = UIColor.clearColor;
    cell.backgroundView = normalBgView;
}

@end
